package com.ruoyi.algorithm.config;

import com.alibaba.fastjson.JSON;
import com.beihu.sightplus.common.response.ResultData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@ControllerAdvice
public class GlobalExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public Object defaultException(HttpServletRequest req, HttpServletResponse response, Exception e) throws Exception {
        StringBuilder sb = new StringBuilder();
        if (req != null) {
            sb.append(String.format("RequestURL: %s %n", req.getRequestURL()));
        }
        logger.error("Request : {}", sb.toString(), e);
        ResultData<String> errorInfo = new ResultData<String>();
        errorInfo.setMsg(e.getMessage());
        errorInfo.setCode(500);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        //具体操作
        writer.write(JSON.toJSONString(errorInfo));
        writer.flush();
        writer.close();
        return null;
    }
}
